<template>
    <div class="publish-article-page">
        <form @submit="() => { return false; }">
            <div class="basic-box">
                <div class="panel-tit">文章信息</div>
                <div class="p-field-control"  id="form_title">
                    <input type="text" v-model="form.title" placeholder="请输入文章名称" maxlength="60"><i class="word-num">{{60-form.title.length}}</i>
                </div>
                <div class="drop-down-control">
                    <div class="flex-ddl-item">
                        <DropDown class="mr20" id="form_categoryId" :list="categoryList" :value.sync="form.categoryId"
                            placeholder="分类" />
                        <DropDown class="mr20" id="form_comeFrom" :list="allCateTypes.sources" :value.sync="form.comeFrom"
                            placeholder="来源" />
                        <DropDown :list="allCateTypes.copyrights" id="form_copyRight" :value.sync="form.copyRight"
                            placeholder="版权" />
                    </div>
                </div>
                <div class="panel-tit mt40">上传封面<span class="small-tip">支持jpg\png\gif格式，建议尺寸800x600px,大小不超过5M</span>
                </div>
                <div id="form_image">
                    <el-upload :action="aliInfo.host" :show-file-list="false" :data="aliData" accept=".jpg,.png,.gif"
                        :on-success="firstPictureSuccess" :drag="true" :before-upload="firstPictureBefore"
                        class="upload-btn">
                        <img loading="lazy" v-if="form.image" :src="form.image" style="width: 100%; height: 100%" class="avatar" />
                    </el-upload>
                </div>
                <div class="panel-tit mt48 flex-between">
                    <div>
                        文章标签<span class="small-tip">添加标签，可以使文章被更多的用户发现（最多添加5个）</span>
                    </div>
                </div>
                <div class="tag-control">
                    <div class="inp-tags">
                        <a class="tag" v-for="(item, i) in form.tags" :key="i">{{ item }}<i class="del-tag"
                                @click="handleClearTag(item, i)"></i></a>
                    </div>
                    <input type="text" v-model="inputValue" maxlength="16" placeholder="按回车键Enter创建标签"
                        @keyup="handleInputConfirm"><i class="num">还可以创建{{5-form.tags.length}}个标签</i>
                </div>
                <div class="recommend-tag-box">
                    <div class="label">推荐标签</div>
                    <div class="tags">
                        <a v-for="(tag, tdx) in tjTags" :key="tdx" class="tag" :class="{ 'active': tag.selected }"
                            @click="chooseTag(tag)">{{ tag.title }}</a>
                    </div>
                </div>

                <div class="panel-tit mt35">其他设置</div>
                <!-- <div class="p-label-field-control">
                    <label>开发商</label><input type="text" placeholder="请输入开发商">
                </div> -->
                <div class="p-label-field-control mt40">
                    <label>评论</label><el-checkbox :true-label="1" class="pro-pbform-ckbox" :false-label="0"
                        v-model="form.commentStatus">关闭评论</el-checkbox>
                </div>
            </div>
            <div class="game-img-workbox">
                <div class="panel-tit flex-between">
                    <div class="tit">编辑文章</div>
                    <!-- <div class="funs">
                        <a class="add-tag">添加标签</a>
                        <a class="batch-mgr-btn">批量管理</a>
                    </div> -->
                </div>
                <div id="form_content" style="height:100%;">
                    <quillEditor ref="myTextEditor" class="pro-quill-editor ar-pro-quill-editor" v-model="form.content"
                    :options="editorOption"></quillEditor>
                </div>
                <!-- <div class="single-upload-btn">
                    <div class="ass-con">
                        <i class="up-text">发布作品</i>
                        <div class="plus">拖拽图片到这里，或 <a class="go-add">点此添加</a></div>
                        <i class="tip">支持jpg/png/gif格式，单个文件最大支持10M</i>
                    </div>
                </div> -->
                <!-- <div class="g-img-mx-harea">
                    <div class="gm-imgs">
                        <div class="g-img-item" :class="{'no-img':i>5}" v-for="i in 30" :key="i">
                            <template v-if="i<6">
                                <img loading="lazy" src="https://img.gameui.net/article-7144-1677380121000@1x456.webp" alt="">
                                <a class="del-btn"></a>
                                <a class="set-tag">设置标签</a>
                            </template>
</div>
</div>
</div>
<div class="bot-single-upload-area">
    <div class="plus">拖拽图片到这里，或 <a class="go-add">点此添加</a></div>
    <span class="tip">已上传 22 张</span>
</div>
<div class="bot-single-upload-area sk-hover">
    <div class="plus-sk">松开上传</div>
    <span class="tip">已上传 22 张</span>
</div> -->
            </div>
        </form>
        <div class="footer-fun-bar">
            <a class="publish" @click="batchArticle(0)">{{ form.id ? '修改' : '发布' }}文章</a>
            <a class="draft" @click="batchArticle(2)">存入草稿</a>
            <a class="preview" @click="handlePreviewFun">预览</a>
        </div>

        <a-modal v-model="showCut" destroyOnClose centered :footer="null" :closable="false" width="840px">
            <div class="cover-win-box">
                <div class="u-header">上传封面 <a class="close-win-box" @click="showCut = false"></a></div>
                <div class="win-modal-con">
                    <div class="left">
                        <img loading="lazy" :src="croPoption.image" ref="gimage" id="gimage" alt="" />
                    </div>
                    <div class="result">
                        <span class="img-box preview-img">

                        </span>
                        <span class="preview-tit">效果预览</span>
                    </div>
                </div>
                <div class="fbar">
                    <el-upload class="again-upload" :action="aliInfo.host" :show-file-list="false" :data="aliData"
                        :on-success="firstPictureSuccess" :before-upload="firstPictureBefore">重新上传</el-upload>
                    <a class="cut-btn" @click="handleConfirmCrop">裁切</a>
                </div>
            </div>
        </a-modal>

        <a-modal v-model="showConfirm" destroyOnClose centered :footer="null" :closable="false" width="408px">
            <div class="confirm-mask">
                <div class="confirm-win">
                    <div class="title">确定要离开吗?</div>
                    <div class="msg">系统可能不会保存填写的信息哦～</div>
                    <div class="btns">
                        <a class="confirm" @click="handleOK">确定</a>
                        <a class="cancel" @click="showConfirm = false">取消</a>
                    </div>
                </div>
            </div>
        </a-modal>

        <el-upload :before-upload="handleUploadAttchFile" accept=".jpg,.png,.gif,jpeg" class="quill-img" action="" name="photos">
        </el-upload>
        <el-upload :before-upload="handleUploadVideoFile" accept=".avi,.mp4,.wmv" class="quill-video" action="" name="photos">
        </el-upload>
    </div>
</template>

<script>
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import api from '@/api/api'
import Video from '@/quill/video'
import { Quill, quillEditor } from "vue-quill-editor";
Quill.register(Video, true)
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import DropDown from '@/components/dropdown'
export default {
    components: {
        DropDown, quillEditor
    },
    data() {
        return {
            isposted:false,
            currentUploadType: 1,
            tjTags: [],
            showConfirm: false,
            nextFun: null,
            inputValue: '',
            showCut: false,
            aliInfo: {
                host: ''
            },
            aliData: {},
            form: {
                content: '',
                title: '',
                images: [],
                activityImages: [],
                imagesBean: {
                    imageList: [],
                    tagNames: ''
                },
                tags: [],
                videoUrl: [{}, {}, {}, {}, {}, {}]
            },
            myCropper: null,
            categoryList: [],
            allCateTypes: {
                categorys: [],
                themes: [],
                funs: [],
                materials: [],
                devices: [],
                orientations: [],
                eras: [],
                styles: [],
                styles: [],
                sources: []
            },
            content: '',
            croPoption: {
                image: "",
                outputSize: 1, // 裁剪生成图片的质量 0.1 - 1
                outputType: "png", //	裁剪生成图片的格式 jpeg || png || webp
                canScale: false, // 图片是否允许滚轮缩放 默认true
                autoCrop: true, // 是否默认生成截图框 默认false
                canMove: true, //上传图片是否可以移动 默认true
                autoCropWidth: 800, //默认生成截图框宽度	容器的80%	0~max
                autoCropHeight: 600, //默认生成截图框高度	容器的80%	0~max
                // fixedBox: true, // 固定截图框大小 不允许改变	false	true | false
                fixed: true, //是否开启截图框宽高固定比例
                original: true, // 上传图片按照原始比例渲染	false	true | false
                infoTrue: true, // 为展示真实输出图片宽高 false 展示看到的截图框宽高	false	true | false
                centerBox: true, // 截图框是否被限制在图片里面	false	true | false
                canMoveBox: false, //截图框能否拖动	true	true | false
                fixedNumber: [1, 1], // 截图框的宽高比例 [宽度, 高度]
            },
            editorOption:
            {
                placeholder: "开始编辑",
                modules: {
                    toolbar:
                    {
                        container: [
                            ["bold", "italic", "underline", "strike"], // 加粗，斜体，下划线，删除线
                            ["blockquote"], // 引用
                            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
                            [{ list: "ordered" }, { list: "bullet" }], //列表
                            [{ indent: "-1" }, { indent: "+1" }], // 缩进
                            [{ direction: "rtl" }], // 文本方向
                            [{ size: ["small", false, "large", "huge"] }], // 字体大小
                            [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
                            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
                            [{ font: [] }], //字体
                            [{ align: [] }], //对齐方式
                            ["clean"], //清除字体样式
                            ["image"], //上传图片、上传视频
                            ["video"], //上传图片、上传视频
                        ],
                        handlers: {
                            image: function (val) {
                                this.currentUploadType = 1;
                                if (val) {
                                    document.querySelector(".quill-img input").click();
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                            video: function (val) {
                                this.currentUploadType = 2;
                                if (val) {
                                    document.querySelector(".quill-video input").click();
                                } else {
                                    this.quill.format("video", false);
                                }
                            }
                        }
                    }
                },
                // 更改插入的图片大小
                imageResize: {
                    displayStyles: {
                        backgroundColor: "black",
                        border: "none",
                        color: "white",
                    },
                    modules: ["Resize", "DisplaySize", "Toolbar"],
                }
            }
        }
    },
    watch:{
        $route(newd){
            if(!newd.params.id){
                this.form={
                    content: '',
                    title: '',
                    images: [],
                    activityImages: [],
                    imagesBean: {
                        imageList: [],
                        tagNames: ''
                    },
                    tags: [],
                    videoUrl: [{}, {}, {}, {}, {}, {}]
                }
            }else{
                this.initQuery();
            }
        }
    },
    destroyed(){
        window.removeEventListener('beforeunload', this.beforeUnload);
    },
    created(){
        window.addEventListener('beforeunload', this.beforeUnload);
    },
    methods: {
        beforeUnload(event) {
            event.preventDefault();
            event.returnValue = '';
        },
        async initQuery() {
            let id = this.$route.params.id;
            let res = {};
            if (id) {
                res = await api.getArticleById(id);
                // content:'',
                //     title:'',
                //     images:[],
                //     activityImages:[],
                //     videoUrl:[{},{},{},{},{},{}]
                let videos = [];
                if (res.data.videoUrl) {
                    let _urls = res.data.videoUrl.split(',');
                    _urls.map(_url => {
                        videos.push({
                            name: _url,
                            url: _url,
                            completed: true,
                            percentage: 100
                        })
                    })
                }
                let model = {
                    id: res.data.id,
                    title: res.data.title,
                    content: res.data.content,
                    images: res.data.imagesBean.imageList ? res.data.imagesBean.imageList.filter(r => { return !r.activity }) : [],
                    activityImages: res.data.imagesBean.imageList ? res.data.imagesBean.imageList.filter(r => { return r.activity == true }) : [],
                    videoUrl: videos,
                    categoryId: res.data.categoryId.toString(),
                    status: res.data.status,
                    commentStatus: res.data.commentStatus,
                    style: res.data.style,
                    device: res.data.device,
                    orientation: res.data.orientation,
                    era: res.data.era,
                    comeFrom: res.data.comeFrom,
                    image: res.data.image,
                    copyRight:res.data.copyRight,
                    tags: res.data.tags ? res.data.tags.split(',') : [],
                    manufacturer: res.data.manufacturer,
                    imagesBean: {
                        tagNames: res.data.imagesBean.tagNames.length > 0 ? res.data.imagesBean.tagNames.join(',') : ''
                    }
                }
                // let model=res.data;
                model.images.map(item => {
                    item.progressno = 100;
                    item.completed = true;
                })
                model.activityImages.map(item => {
                    item.progressno = 100;
                })
                this.form = model;
            }
        },
        handleUploadAttchFile(f) {
            let _fdata = new FormData();
            _fdata.append('file', f);

            let that = this;
            // const loading = this.$loading({
            //     lock: true,
            //     text: '上传中...',
            //     spinner: 'el-icon-loading',
            //     background: 'rgba(0, 0, 0, 0.7)'
            // });

            let _formdata = new FormData();
            
            let fileUrlKey = that.aliInfo.dir + '/' + new Date().getTime() + f.name;
            _formdata.append("key", fileUrlKey);

            _formdata.append("file", f);

            $.ajax({
                url: that.aliInfo.host,
                type: "POST",
                cache: false,
                data: _formdata,
                processData: false,
                contentType: false,
                dataType: "json",
                success: function (updata) {
                    // loading.close();
                    //if (updata.code == 0) {
                        // 获取富文本组件实例
                        let quill = that.$refs.myTextEditor.quill;
                        // 如果上传成功
                        // 获取光标所在位置
                        let length = quill.getSelection().index;
                        // 插入图片 res.data为服务器返回的图片地址
                        quill.insertEmbed(length, 'image', that.$savePublishAlihost+'/' + fileUrlKey + '?x-oss-process=style/default');// 这里的url是图片的访问路径不是真实物理路径
                        // 调整光标到最后
                        quill.setSelection(length + 1)
                    // } else {
                    //     that.$amessage.error(updata.msg)
                    // }
                },
                error: function (res) {
                    
                }
            });
            return;
            $.ajax({
                url: thiis.aliInfo.host,
                type: "POST",
                headers: {
                    'token': localStorage.getItem('token')
                },
                cache: false,
                data: _fdata,
                processData: false,
                contentType: false,
                dataType: "json",
                success: function (updata) {
                    // loading.close();
                    if (updata.code == 0) {
                        // 获取富文本组件实例
                        let quill = that.$refs.myTextEditor.quill;
                        // 如果上传成功
                        // 获取光标所在位置
                        let length = quill.getSelection().index;
                        // 插入图片 res.data为服务器返回的图片地址
                        quill.insertEmbed(length, 'image', updata.data + '?x-oss-process=style/default');// 这里的url是图片的访问路径不是真实物理路径
                        // 调整光标到最后
                        quill.setSelection(length + 1)
                    } else {
                        that.$amessage.error(updata.msg)
                    }
                },
                error: function (res) {
                    // loading.close();

                    that.$amessage.error(res.responseJSON.msg)
                }
            });
            return false;
        },
        handleUploadVideoFile(f) {
            let _fdata = new FormData();
            _fdata.append('file', f);

            let that = this;
            // const loading = this.$loading({
            //     lock: true,
            //     text: '上传中...',
            //     spinner: 'el-icon-loading',
            //     background: 'rgba(0, 0, 0, 0.7)'
            // });

            let _formdata = new FormData();
            
            let fileUrlKey = that.aliInfo.dir + '/' + new Date().getTime() + f.name;
            _formdata.append("key", fileUrlKey);

            _formdata.append("file", f);

            $.ajax({
                url: that.aliInfo.host,
                type: "POST",
                cache: false,
                data: _formdata,
                processData: false,
                contentType: false,
                dataType: "json",
                success: function (updata) {
                    // loading.close();
                    //if (updata.code == 0) {
                        // 获取富文本组件实例
                        let quill = that.$refs.myTextEditor.quill;
                        // 如果上传成功
                        // 获取光标所在位置
                        let length = quill.getSelection().index;
                        // 插入图片 res.data为服务器返回的图片地址
                        quill.insertEmbed(length, 'video', that.$savePublishAlihost+'/' + fileUrlKey );// 这里的url是图片的访问路径不是真实物理路径
                        // 调整光标到最后
                        quill.setSelection(length + 1)
                    // } else {
                    //     that.$amessage.error(updata.msg)
                    // }
                },
                error: function (res) {
                    
                }
            });
        },
        handleClearTag(tag, idx) {
            this.form.tags.splice(idx, 1);
            this.tjTags.map(item => {
                if (item.title == tag) {
                    item.selected = false;
                }
            })
            this.$forceUpdate();
        },
        chooseTag(tag) {
            if (this.form.tags.length == 5) {
                this.$amessage.warn('最多可添加5个标签！')
                return;
            }
            tag.selected = tag.selected == undefined ? true : !tag.selected;
            if (tag.selected) {
                this.form.tags.push(tag.title)
            } else {
                let items = this.form.tags.filter(r => {
                    return r != tag.title;
                })
                this.form.tags = items;
            }
            this.$forceUpdate();
        },
        handleOK() {
            this.nextFun();
        },
        handleInputConfirm(e) {
            let _value = e.target.value;
            if (!_value || !_value.replace(/\s+/g, "")) {
                e.target.value = "";
                return;
            }
            if (e.key == "Enter") {
                if (this.form.tags.length >= 5) {
                    this.$amessage.warn("最多可添加5个标签！");

                    this.inputValue = '';
                    return;
                }

                this.form.tags.push(_value);
                this.inputValue = '';
            }
        },
        dataURLtoBlob(dataurl) {
            var arr = dataurl.split(","),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        },
        handleConfirmCrop() {
            if (!this.croPoption.image) {
                this.$amessage.warn("请先选择图片");
                return;
            }
            let that = this;

            let data = that.myCropper.getCroppedCanvas({
                imageSmoothingQuality: 'high'
            }).toDataURL('image/jpeg')
            data = that.dataURLtoBlob(data);

            let _formdata = new FormData();

            let fileUrlKey = that.aliInfo.dir + '/' + new Date().getTime() + that.cropFileName;
            _formdata.append("key", fileUrlKey);
            for (let p in that.aliParamsData) {
                _formdata.append(p, that.aliParamsData[p]);
            }

            _formdata.append("file", data);
            // let index = layer.load(0, { shade: false });
            $.ajax({
                url: that.aliInfo.host,
                type: "POST",
                cache: false,
                data: _formdata,
                processData: false,
                contentType: false,
                dataType: "json",
                success: function (updata) {
                    // layer.close(index);
                    that.form.image = that.$savePublishAlihost+'/' + fileUrlKey;
                    that.$amessage.success("上传成功");
                    that.handleClearCrop();
                },
                error: function (res) {
                    // layer.close(index);

                    that.$amessage.error('上传服务器异常~')
                }
            });
        },
        handleClearCrop() {
            this.showCut = false;
            // $('.cropper-container').remove();
            this.myCropper.destroy();
        },
        /* 封面上传 */
        firstPictureBefore(file) {
            this.cropFileName = file.name;
            var isImage = file.type === "image/jpg";

            if (!isImage) isImage = file.type === "image/jpeg";
            if (!isImage) isImage = file.type === "image/png";
            if (!isImage) isImage = file.type === "image/gif";

            const sizeFalg = file.size / 1024 / 1024 < 5;
            if (!isImage) {
                this.$amessage.warn("封面只能是[JPG,PNG,GIF]格式!");
                return false;
            }
            if (!sizeFalg) {
                this.$amessage.warn("封面大小不能超过 5MB!");
                return false;
            }

            let that = this;
            this.aliData.key = this.aliInfo.dir + "/" + new Date().getTime() + file.name;
            let reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function () {
                let img = new Image();
                img.onload = function () {
                    that.croPoption.image = reader.result;

                    that.$forceUpdate();

                    if (!that.showEditCover) {
                        that.activeUploadCoverIndex = false;
                        that.showCut = true;
                    }
                    if (that.myCropper) {
                        that.myCropper.destroy();
                    }
                    that.initCropper();
                    // }
                };
                img.src = reader.result;
            };
            return false;
        },
        initCropper() {
            let that = this;
            that.$nextTick(() => {
                that.myCropper = new Cropper(that.$refs.gimage, {
                    viewMode: 1,
                    cropBoxResizable: true,
                    autoCropArea: 1,
                    aspectRatio: 104 / 78,
                    preview: ".preview-img",
                    dragMode: "move",
                    toggleDragModeOnDblclick: false
                });
            });
        },
        firstPictureSuccess(err, file, fileList) {
            let img = new Image();
            let _URL = window.URL || window.webkitURL;
            let that = this;
            img.onload = function () {
                if (img.width != 800 && img.height != 600) {
                    that.addArticleParam.image = "";
                    that.$amessage.warn("建议尺寸800x600");
                } else {
                    that.$amessage.warn("封面上传成功！");
                    that.addArticleParam.image = that.serverUrl + "/" + that.aliData.key;
                }
            };
            img.src = this.serverUrl + "/" + this.aliData.key;
        },
        resetForm() {
            this.form = {
                content: '',
                title: '',
                images: [],
                activityImages: [],
                imagesBean: {
                    imageList: [],
                    tagNames: ''
                },
                tags: [],
                videoUrl: [{}, {}, {}, {}, {}, {}]
            }
        },
        handlePreviewFun() {
            let that = this;
            this.batchArticle(2, function (calldata) {
                that.$router.push({ path: "/article/" + calldata.data.id })
            })
        },
        async batchArticle(_status, callback) {
            if(this.isposted==true){
                this.$amessage.warn('服务器正在处理,请勿频繁操作~');
                return;
            }
            let data = Object.assign({}, this.form);
            data.status = _status;
            data.images = [...data.images, ...data.activityImages];
            let videos = [];
            data.videoUrl.map(item => {
                if (item.url && item.percentage == 100) {
                    videos.push(item.url)
                }
            })
            let imgs = [];
            data.images.map(i => {
                if (i.completed) {
                    imgs.push({ url: i.url, tags: i.tags, imageWidth: i.imageWidth, imageHeight: i.imageHeight, activity: i.activity ? true : false })
                }
            })
            // let activityImgs=[];
            // data.activityImages.map(i=>{
            //     if(i.completed){
            //         activityImgs.push({url:i.url,tags:i.tags,imageWidth:i.imageWidth,imageHeight:i.imageHeight})
            //     }
            // })
            delete data.images;
            // data.imagesBean={imageList:[],tagNames:[]};
            data.commentStatus = parseInt(data.commentStatus);
            data.imagesBean.imageList = imgs;
            data.tags = data.tags.join(',');
            if (data.imagesBean.tagNames.length > 0) {
                data.imagesBean.tagNames = data.imagesBean.tagNames.split(',');
            } else {
                data.imagesBean.tagNames = [];
            }

            delete data.themes;

            data.videoUrl = videos.join(',');
            delete data.activityImages;
            let res = {};

            $('.null-error').removeClass('null-error');
            if(!data.title){
                $('#form_title').addClass('null-error');
                this.$amessage.warn('请先将信息未填写完整~');
                return;
            }
            if(!data.content){
                $('#form_content').addClass('null-error');
                this.$amessage.warn('请先将信息未填写完整~');
                return;
            }
            if(!data.categoryId){
                $('#form_categoryId').addClass('null-error');
                this.$amessage.warn('请先将信息未填写完整~');
                return;
            }
            if(!data.comeFrom){
                $('#form_comeFrom').addClass('null-error');
                this.$amessage.warn('请先将信息未填写完整~');
                return;
            }
            if(!data.copyRight){
                $('#form_copyRight').addClass('null-error');
                this.$amessage.warn('请先将信息未填写完整~');
                return;
            }
            if(!data.image){
                $('#form_image').addClass('null-error');
                this.$amessage.warn('请先将信息未填写完整~');
                return;
            }
            this.isposted=true;
            if (data.id) {
                res = await api.editArticle(data);
                if (res.code == 0) {
                    this.$bhelper.addCirRecord('ARTICLE');
                    this.$store.dispatch('setLeftMenu',[])
                    this.resetForm();
                    this.isposted=false;
                    this.$amessage.success('更新成功！快去告诉你的粉丝们')
                    this.$router.replace({ path: '/publish/publishManage?t=0&s=9' })
                }
            } else {
                res = await api.addArticle(data);
                if (res.code == 0) {
                    this.$bhelper.addCirRecord('ARTICLE');
                    this.$store.dispatch('setLeftMenu',[])
                    this.resetForm();
                    this.isposted=false;
                    if (!callback) {
                        this.$amessage.success('发布成功！准备接受掌声吧')
                        this.$router.replace({ path: '/publish/publishManage?t=0&s=9' })
                    } else {
                        callback(res);
                    }
                }
            }
        }
    },
    beforeRouteLeave(to, from, next) {
        let data = this.form;
        this.nextFun = next;
        if (data.title || data.content || data.categoryId || data.comeFrom || data.copyRight || data.manufacturer || data.commentStatus > 0 || data.image) {
            this.showConfirm = true;
        } else {
            next()
        }
    },
    async mounted() {
        $('#app').removeClass('info-detail-page');
        let _allCateTypes = JSON.parse(decodeURIComponent(localStorage.getItem('OBJ-CATE-ALL-TYPES')));
        let res = await api.getAttributes({ type: 'from', categoryId: 22 })
        res.data.from.map(item => {
            item.title = item.name;
            item.value = item.name;
        })
        _allCateTypes.sources = res.data.from;
        res = await api.getAttributes({ type: 'copyright', categoryId: 22 })
        res.data.copyright.map(item => {
            item.title = item.name;
            item.value = item.name;
        })
        _allCateTypes.copyrights = res.data.copyright;
        this.allCateTypes = _allCateTypes;

        this.initQuery();

        res = await api.getChildrenListByParentId({ parentId: 9 })
        res.data.map(item => {
            item.value = item.id.toString();
        })
        this.categoryList = res.data;
        res = await api.getImgPoc();


        this.aliInfo = res.data;

        res = await api.getCategoryForInspiration({ categoryId: 1 })
        this.tjTags = res.data.filter(r => {
            return r.key == 'theme';
        })[0].result.splice(1, 20);

        
        this.$nextTick(() => {
            if($('.t-adv').length>0){
                $('#app').addClass('b-has-adv');
            }
        })
    }
}
</script>

<style lang="less">
.publish-article-page {
    form {
        display: flex;
    }
    
    .null-error{
        input{
            border:1px solid #11CCB1 !important;
            border-radius: 8px;
        }
        .pro-quill-editor{
            border:1px solid #11CCB1 !important;
            border-radius: 8px;
        }
        .cur{
            border:1px solid #11CCB1 !important;
        }
        .upload-btn{
            border-color:#11CCB1 !important;
        }
    }

    .panel-tit {
        font-weight: 500;
        font-size: 16px;
        line-height: 22px;
        margin-bottom: 20px;

        .small-tip {
            font-size: 12px;
            color: #6A6A80;
            margin-left: 14px;
        }

        &.flex-between {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .add-tag {
            line-height: 38px;
            width: 97px;
            text-align: center;
            border-radius: 10px;
            background: #29272F;
            color: #fff;
            display: inline-block;
            margin-right: 11px;
            font-size: 14px;
        }

        .batch-mgr-btn {
            line-height: 38px;
            width: 97px;
            text-align: center;
            border-radius: 10px;
            background: #29272F;
            color: #fff;
            display: inline-block;
            font-size: 14px;
        }
    }

    .basic-box {
        width: 50%;
        background: #181818;
        border-radius: 16px;
        padding: 29px 30px;

        .drop-down-control {
            display: flex;
            flex-wrap: wrap;

            .flex-ddl-item {
                display: flex;
                align-items: center;
                margin-bottom: 10px;
                width:100%;
                .mk-cus-ddl{
                    width:100% !important;
                }
            }
        }

        .mt40 {
            margin-top: 40px;
        }

        .mt35 {
            margin-top: 35px;
        }

        .mt48 {
            margin-top: 48px;
        }

        .p-field-control {
            border-radius: 8px;
            overflow: hidden;
            position: relative;
            margin-bottom: 10px;

            input[type="text"] {
                height: 40px;
                padding-left: 14px;
                border: none;
                width: 100%;
                background: #23232A;
                color: #fff;
                font-size: 14px;
                padding-right: 40px;
            }

            textarea {
                height: 80px;
                padding-left: 14px;
                border: none;
                width: 100%;
                background: #23232A;
                color: #fff;
                font-size: 14px;
                padding-right: 40px;
                resize: none;
                padding-top: 10px;
            }

            .word-num {
                position: absolute;
                right: 14px;
                font-style: normal;
                color: #969696;
                top: 10px;

                &.bot-r {
                    bottom: 10px;
                    top: inherit;
                }
            }
        }

        .import-video-btn {
            line-height: 38px;
            width: 97px;
            text-align: center;
            border-radius: 10px;
            background: #29272F;
            color: #fff;
            font-size: 14px;
        }

        .p-label-field-control {
            border-radius: 8px;
            overflow: hidden;
            position: relative;
            margin-bottom: 10px;
            display: flex;
            align-items: center;

            input[type="text"] {
                height: 40px;
                padding-left: 14px;
                border: none;
                width: 100%;
                background: #23232A;
                color: #fff;
                font-size: 14px;
                padding-right: 40px;
            }

            label {
                color: #fff;
                font-size: 14px;
                margin-right: 36px;
                white-space: nowrap;
                min-width: 40px;
            }

            .word-num {
                position: absolute;
                right: 14px;
                font-style: normal;
                color: #969696;
                top: 10px;

                &.bot-r {
                    bottom: 10px;
                    top: inherit;
                }
            }
        }

        .upload-btn {
            width: 210px;
            height: 160px;
            border-radius: 10px;
            border: 2px dashed #52525C;
            cursor: pointer;
            display: block;
            overflow: hidden;
            background: inherit !important;

            .el-upload {
                width: 100%;
                height: 100%;
            }

            .el-upload-dragger {
                background-color: #181818;
                width: 100%;
                border: none;
                height: 100%;
                background: url('../../assets/pro/upload_cover.svg') no-repeat;
                background-position: center;
                background-size: 40px 40px;
            }
        }

        .upload-video-btn {
            width: 210px;
            height: 118px;
            border-radius: 10px;
            border: 2px dashed #52525C;
            background: url('../../assets/pro/upload_cover.svg') no-repeat;
            background-position: center;
            background-size: 40px 40px;
            cursor: pointer;
            display: block;
        }
    }

    .tag-control {
        height: 40px;
        border-radius: 8px;
        overflow: hidden;
        display: flex;
        align-items: center;
        padding-left: 5px;
        background: #23232A;
        margin-bottom: 20px;
        position: relative;

        .inp-tags {
            display: flex;
            align-items: center;

            .tag {
                line-height: 30px;
                padding-left: 15px;
                padding-right: 12px;
                border-radius: 30px;
                white-space: nowrap;
                margin-right: 5px;
                background: #33333C;
                height: 100%;
                display: inline-block;
                font-size: 14px;

                .del-tag {
                    width: 10px;
                    height: 10px;
                    background: url('../../assets/pro/del_tag_ico.svg') no-repeat;
                    background-size: cover;
                    display: inline-block;
                    margin-left: 11px;
                    opacity: .8;

                    &:hover {
                        opacity: 1;
                    }
                }
            }
        }

        input {
            background: #23232A;
            color: #fff;
            font-size: 14px;
            width: 100%;
            padding-left: 13px;
            border: none;
        }

        .num {
            font-style: normal;
            font-size: 14px;
            color: #6A6A80;
            position: absolute;
            right: 10px;
            top: 10px;
            z-index: 11;
            background: #23232A;
            padding-left: 10px;
        }
    }

    .recommend-tag-box {
        display: flex;
        align-items: baseline;
        font-size: 14px;
        margin-top: 15px;
        flex-wrap: wrap;

        .label {
            margin-right: 30px;
            white-space: nowrap;
        }

        .tags {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            grid-gap: 10px;
            flex: 1;

            .tag {
                line-height: 30px;
                border-radius: 30px;
                padding: 0px 15px;
                background: #242327;
                color: #fff;

                // margin-right:30px;
                &.active {
                    background: #11CCB1;
                }
            }
        }
    }

    .game-img-workbox {
        margin-left: 20px;
        width: 50%;
        background: #181818;
        border-radius: 16px;
        min-height:300px;

        padding: 29px 30px;
        overflow: hidden;
        .single-upload-btn {
            background-color: #23232A;
            border: 2px dashed #4E4E57;
            border-radius: 16px;
            width: 700px;
            height: 400px;
            background-image: url('../../assets/pro/single_upload_bgico.svg');
            background-repeat: no-repeat;
            background-size: 90px 90px;
            background-position: center 30%;
            display: block;
            position: relative;
            text-align: center;

            i {
                font-style: normal;
            }

            .ass-con {
                position: absolute;
                bottom: 20px;
                left: 0px;
                right: 0px;

                .up-text {
                    font-size: 20px;
                    font-weight: 500;
                    display: block;
                    line-height: 28px;
                }

                .tip {
                    color: #6A6A80;
                    font-size: 14px;
                    display: block;
                    margin-top: 76px;
                    line-height: 20px;

                    &.mx-w459 {
                        max-width: 459px !important;
                        margin: 0 auto;
                        margin-top: 50px;
                    }
                }

                .plus {
                    // background:url('../../assets/pro/upload_cover.svg') no-repeat;
                    // background-position:left center;
                    // background-size:22px 22px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    padding-left: 30px;
                    margin-top: 25px;
                    line-height: 22px;
                    font-weight: 500;
                    margin-bottom: 14px;
                    font-size: 14px;
                    line-height: 20px;

                    .go-add {
                        font-size: 16px;
                        color: #11CCB1;
                        font-weight: 500;
                        text-decoration: underline;
                        margin-left: 3px;

                        >div:last-child {
                            position: absolute !important;
                            left: 0 !important;
                            top: 0 !important;
                            height: 100% !important;
                            width: 100% !important;
                            opacity: 0;
                        }
                    }
                }
            }
        }

        .g-img-mx-harea {
            max-height: 600px;
            overflow-y: auto;
            position: relative;

            &::-webkit-scrollbar {
                width: 6px;
                height: 8px;
                background-color: transparent;
            }

            /*滚动条的轨道*/
            &::-webkit-scrollbar-track {
                background-color: transparent;
            }

            /*滚动条的滑块按钮*/
            &::-webkit-scrollbar-thumb {
                border-radius: 6px;
                background-color: #29272F;
            }

            /*滚动条的上下两端的按钮*/
            &::-webkit-scrollbar-button {
                height: 0;
            }

            /* 两个滚动条的交汇处 */
            &::-webkit-scrollbar-corner {
                background-color: transparent;
            }
        }

        .mt31 {
            margin-top: 31px;
        }

        .gm-imgs {
            display: flex;
            flex-wrap: wrap;

            .g-img-item {
                width: 130px;
                height: 98px;
                border-radius: 8px;
                overflow: hidden;
                margin-right: 10px;
                margin-bottom: 10px;
                user-select: none;
                position: relative;

                &:nth-child(5n) {
                    margin-right: 0px;
                }

                >img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                .del-btn {
                    width: 30px;
                    height: 30px;
                    background: url('../../assets/pro/del_gm_img.svg') no-repeat;

                    position: absolute;
                    left: calc((100% - 30px) / 2);
                    top: calc((100% - 30px) / 2 - 15px);
                }

                .set-tag {
                    position: absolute;
                    left: calc((100% - 79px) / 2);
                    top: calc((100% - 26px) / 2 + 20px);
                    background: rgba(0, 0, 0, 0.4);
                    width: 79px;
                    line-height: 26px;
                    text-align: center;
                    border-radius: 13px;
                    line-height: 26px;
                    color: #fff;
                }

                &.no-img {
                    border: 1px dashed #52525C;
                }
            }
        }
    }

    .bot-single-upload-area {
        text-align: center;
        height: 105px;
        border: 2px dashed #52525C;
        border-radius: 16px;
        user-select: none;
        background: #23232A;

        .plus {
            background: url('../../assets/pro/upload_cover.svg') no-repeat;
            background-position: left center;
            background-size: 22px 22px;
            display: inline-block;
            padding-left: 30px;
            margin-top: 25px;
            line-height: 22px;
            margin-bottom: 14px;

            .go-add {
                font-size: 16px;
                color: #11CCB1;
                font-weight: 500;
                text-decoration: underline;
                margin-left: 3px;
            }
        }

        .plus-sk {
            background: url('../../assets/pro/sk_upload_ico.svg') no-repeat;
            background-position: left center;
            background-size: 22px 22px;
            display: inline-block;
            padding-left: 30px;
            margin-top: 25px;
            line-height: 22px;
            margin-bottom: 14px;
        }

        .tip {
            font-size: 14px;
            color: #969696;
            font-weight: 500;
            display: block;
        }

        &.sk-hover {
            border-color: #11CCB1;
            background-color: #250C12;
        }
    }

    .footer-fun-bar {
        padding: 18px 0px;
        // text-align: right;
        user-select: none;

        >a {
            display: inline-block;
            line-height: 44px;
            font-size: 16px;
            font-weight: 500;
            &:not(.publish):hover{
                background:#393740;
            }
        }

        .draft {
            background: #29272F;
            color: #fff;
            width: 120px;
            text-align: center;
            border-radius: 10px;
            margin-left:10px;
        }

        .preview {
            background: #29272F;
            color: #fff;
            width: 110px;
            text-align: center;
            border-radius: 10px;
            margin: 0px 10px;
        }

        .publish {
            background: #11CCB1;
            color: #fff;
            padding:0px 20px;
            // width: 110px;
            text-align: center;
            border-radius: 10px;
        }
    }
}
</style>